package com.byx.chatclient.presenter.user;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;

import com.byx.chatclient.ChatApp;
import com.byx.chatclient.bean.LoginDropDownBean;
import com.byx.chatclient.contract.user.LoginTaskContract;
import com.byx.chatclient.entity.UserPo;
import com.byx.chatclient.http.HttpFilesUtil;
import com.byx.chatclient.model.LoginModel;
import com.byx.chatclient.pojo.LoginDto;
import com.byx.chatclient.pojo.LoginVo;
import com.byx.chatclient.presenter.BasePresenter;
import com.byx.chatclient.service.NettyService;
import com.byx.chatclient.utils.FileUtils;
import com.byx.chatclient.utils.ValidateUtil;
import com.byx.chatclient.view.activity.user.LoginActivity;

import java.util.List;

/**
 * LoginPresenter
 *
 * @author Superb
 * @date 2021/2/22 10:20
 */
public class LoginPresenter extends BasePresenter<LoginActivity> implements LoginTaskContract.Presenter {
    private static final String TAG = LoginPresenter.class.getSimpleName();
    private final LoginModel loginModel;

    public LoginPresenter() {
        loginModel=new LoginModel(ChatApp.getInstance());
    }

    private void success(String loginId){
        //从本地数据库中取出用户信息，缓存在内存
        UserPo userPo = loginModel.queryUserPoById(loginId);
        ChatApp.getInstance().saveCurrentUser(userPo);
        view.hideLoading();
        //开启服务
        view.startService(new Intent(view.getApplicationContext(), NettyService.class));
        view.onSuccess();
    }

    @Override
    public void login(){
        if (isActive()){
            LoginVo loginVo = view.getLoginVo();
            if (!ValidateUtil.isLoginIdValid(loginVo.getLoginId())) {
                view.onError("账号格式不正确");
            }else if (!ValidateUtil.isPasswordValid(loginVo.getPassword())){
                view.onError("密码必须由数字和字母组成");
            }else {
                String password = loginVo.getPassword();
                loginVo.setPassword(ValidateUtil.encodeByMd5(password));
                view.showLoading();

                loginModel.login(loginVo, new LoginTaskContract.Model.LoginCallBack<LoginDto>() {
                    @Override
                    public void onSuccess(LoginDto data) {
                        final boolean[] flag = {false};
                        if (data != null){
                            UserPo userPo = loginModel.queryUserPoById(loginVo.getLoginId());
                            //如果服务端返回的用户信息不为空，说明数据不一致，需要更新，则保存用户信息，密码通过Base64加密保存
                            if (userPo == null || userPo.getLocalAvatarUrl() == null ||
                                    !data.getAvatar().equals(userPo.getRemoteAvatarUrl()) ||
                                    !FileUtils.isFileExists(userPo.getLocalAvatarUrl())) {
                                String path = ChatApp.getInstance().getExternalFilesDir(null).getAbsolutePath() + "/avatar";
                                if (FileUtils.createOrExistsDir(path)){
                                    flag[0] = true;
                                    String name = data.getAvatar();
                                    String finalName = path + name.substring(name.lastIndexOf('/'));
                                    HttpFilesUtil.download(finalName, name, new HttpFilesUtil.DownloadCallBack() {
                                        @Override
                                        public void onSuccess() {
                                            loginModel.saveLoginInfo(data,ValidateUtil.encodeByBase64(password), finalName);
                                            success(loginVo.getLoginId());
                                        }

                                        @Override
                                        public void onFailure(Throwable t) {

                                        }
                                    });
                                }
                            }else {
                                loginModel.saveLoginInfo(data,ValidateUtil.encodeByBase64(password),userPo.getLocalAvatarUrl());
                            }
                        }
                        if (!flag[0]){
                            success(loginVo.getLoginId());
                        }
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        view.onError(msg,code);
                    }

                    @Override
                    public void onAccountError() {
                        view.onError("用户名不存在");
                    }

                    @Override
                    public void onPasswordError() {
                        view.onError("密码错误");
                    }

                    @Override
                    public void onUpdate(float progress) {
                        view.onUpdate(progress);
                    }
                });
            }
        }
    }

    /**
     * 获取登录信息
     *
     * @return
     */
    @Override
    public List<LoginDropDownBean> getLoginInfo() {
        return loginModel.getLoginInfo();
    }

    public void deleteByLoginId(String loginId){
        loginModel.deleteUserPo(loginId);
    }
}
